#!/usr/bin/env bash

set -Eeuo pipefail

log() {
	echo "[$(date '+%Y/%m/%d %H:%M:%S')] $*"
}

# 进入 NestJS 项目目录（相对本脚本位置）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR/nestjs-app"

# 必要环境变量（可在 Jenkins/CI 中通过环境注入覆盖）
export PORT="${PORT:-8206}"
export DB_HOST="${DB_HOST:-43.143.253.188}"
export DB_PORT="${DB_PORT:-3306}"
export DB_USER="${DB_USER:-nextjs}"
export DB_PASS="${DB_PASS:-yEAiRE2jcxTyRBy5}"
export DB_NAME="${DB_NAME:-nextjs}"

log "Jenkins macOS build starting..."

log "Installing dependencies..."
if ! npm ci --no-audit --no-fund; then
	log "npm ci failed, fallback to npm install"
	npm install --no-audit --no-fund
fi

log "Building project..."
npm run build

log "Deploying with PM2..."
if ! command -v pm2 >/dev/null 2>&1; then
	log "PM2 not found, installing globally..."
	npm install -g pm2
fi

export NODE_ENV=production

# 若已存在同名进程则 reload，否则 start
if ! pm2 describe nestjs-app >/dev/null 2>&1; then
	log "Starting PM2 process nestjs-app ..."
	pm2 start dist/main.js --name nestjs-app --time --update-env
else
	log "Reloading PM2 process nestjs-app ..."
	pm2 reload nestjs-app --update-env
fi

# 保存 PM2 列表（若已配置 pm2 startup，则可自启）
pm2 save

log "Build succeeded."
